﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight;
using System.Windows.Input;
using Service;
using Microsoft.Practices.ServiceLocation;
using GalaSoft.MvvmLight.Views;
using GalaSoft.MvvmLight.Messaging;
using Common;
using System.ComponentModel;

namespace ViewModel.AlertCreate
{
    public class AlertDocEditViewModel : ViewModelBase
    {
        public ViewModelBase ParentViewModel { get; set; }

        private TagObjectInfo NonSelectedTag = new TagObjectInfo { TagObjectName = "未选择标签" };
        private IEnumerable<TagObjectInfo> m_TagInfoList;
        public IEnumerable<TagObjectInfo> TagInfoList
        {
            get { return this.m_TagInfoList; }
            set { this.m_TagInfoList = value; base.RaisePropertyChanged(() => TagInfoList); }
        }

        private string NonSelectedIndustry = "未选择行业";
        private IEnumerable<string> m_IndustryList;
        public IEnumerable<string> IndustryList
        {
            get { return this.m_IndustryList; }
            set { this.m_IndustryList = value; base.RaisePropertyChanged(() => IndustryList); }
        }

        private ElementInfo NonSelectedElement = new ElementInfo { ElementName = "未选择要素" };
        private IEnumerable<ElementInfo> m_ElementList;
        public IEnumerable<ElementInfo> ElementList
        {
            get { return m_ElementList; }
            set { this.m_ElementList = value; base.RaisePropertyChanged(() => this.ElementList); }
        }

        private TagObjectInfo m_CurrentTagInfo;
        public TagObjectInfo CurrentTagInfo
        {
            get { return m_CurrentTagInfo; }
            set { this.m_CurrentTagInfo = value; base.RaisePropertyChanged(() => CurrentTagInfo); }
        }

        private string m_CurrentIndustry;
        public string CurrentIndustry
        {
            get { return this.m_CurrentIndustry; }
            set { this.m_CurrentIndustry = value; base.RaisePropertyChanged(() => CurrentIndustry); }
        }

        private ElementInfo m_CurrentElement;
        public ElementInfo CurrentElement
        {
            get { return this.m_CurrentElement; }
            set { this.m_CurrentElement = value; base.RaisePropertyChanged(() => CurrentElement); }
        }

        private AlertDoc m_AlertDoc = new AlertDoc();
        public AlertDoc AlertDoc
        {
            get { return m_AlertDoc; }
            set { this.m_AlertDoc = value; base.RaisePropertyChanged(() => AlertDoc);
            }
        }

        public ICommand AlertDocEditCommand { get; set; }
        public ICommand CancelCommand { get; set; }
        private IAlertDocService m_AlertDocService;
        private IUserService m_UserManagementService;
        private ITagInfoService m_TagInfoService;
        private IElementService m_ElementService;

        public AlertDocEditViewModel(IAlertDocService alertDocService, IUserService userManagerService, ITagInfoService tagInfoService, IElementService elementService)
        {
            this.m_AlertDocService = alertDocService;
            this.m_UserManagementService = userManagerService;
            this.m_TagInfoService = tagInfoService;
            this.m_ElementService = elementService;
            this.AlertDocEditCommand = new RelayCommand(AlertDocEdit);
            this.CancelCommand = new RelayCommand(CloseWindow);
            this.RefreshData(() => { this.PropertyChanged += OnPropertyChange; });
        }

        private void OnPropertyChange(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName.Equals("AlertDoc"))
            {
                SyncDataWhenAlertDocChange();
            }
        }

        private void SyncDataWhenAlertDocChange()
        {
            this.CurrentTagInfo = this.TagInfoList.FirstOrDefault(tag=>tag.TagId == this.AlertDoc.TagObjectInfo.TagId) ?? this.NonSelectedTag;
            this.CurrentIndustry = this.IndustryList.FirstOrDefault(industry => industry == this.AlertDoc.UserIndustry) ?? this.NonSelectedIndustry;
            this.CurrentElement = this.ElementList.FirstOrDefault(element => element.ElementName == this.AlertDoc.ElementName) ?? this.NonSelectedElement;
        }

        private async void RefreshData(Action afterRefresh = null)
        {
            try
            {
                IEnumerable<TagObjectInfo> tagInfos = await this.m_TagInfoService.QueryTagInfosAsync();
                List<TagObjectInfo> tagInfoList = new List<TagObjectInfo> { this.NonSelectedTag };
                tagInfoList.AddRange(tagInfos);
                this.TagInfoList = tagInfoList;

                IEnumerable<string> industrys = await this.m_UserManagementService.QueryUserIndustry();
                List<string> industryList = new List<string> { this.NonSelectedIndustry };
                industryList.AddRange(industrys);
                this.IndustryList = industryList;

                IEnumerable<ElementInfo> elementInfos = await this.m_ElementService.QueryElementsAsync("自建站");
                List<ElementInfo> elementInfoList = new List<ElementInfo> { this.NonSelectedElement };
                elementInfoList.AddRange(elementInfos);
                this.ElementList = elementInfoList;

                if (afterRefresh != null)
                {
                    afterRefresh.Invoke();
                }
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError("加载数据失败", "错误", "确定", null);
                Log.WriteException(ex);
            }
        }

        private async void AlertDocEdit()
        {
            if (string.IsNullOrEmpty(this.AlertDoc.Content))
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("内容不能为空","校验失败");
                return;
            }

            AlertDoc alertDoc = this.AlertDoc;

            if (this.CurrentTagInfo != null && this.CurrentTagInfo != this.NonSelectedTag)
            {
                alertDoc.TagObjectInfo = this.CurrentTagInfo;
            }
            if (!string.IsNullOrEmpty(this.CurrentIndustry) || this.CurrentIndustry != this.NonSelectedIndustry)
            {
                alertDoc.UserIndustry = this.CurrentIndustry;
            }

            if (this.CurrentElement != null && this.CurrentElement != this.NonSelectedElement)
            {
                alertDoc.ElementName = CurrentElement.ElementName;
            }

            alertDoc.InsertTime = DateTime.Now;
            alertDoc.AddMan = AppSetting.Instance.User.UserId;
            
            try
            {
                Task task = this.m_AlertDocService.InsertOrUpdateAlertDoc(alertDoc);
                task.Wait();
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("保存成功", "校验失败");

                this.MessengerInstance.Send<object>(null, "AlertDoc_CloseEditForm");
                (this.ParentViewModel as AlertDocViewModel)?.RefreshData();
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError("加载数据失败", "错误", "确定", null);
                Log.WriteException(ex);
            }
        }

        private void CloseWindow()
        {
            Messenger.Default.Send<object>(null, "AlertDoc_CloseEditForm");   
        }
    }
}
